<template>
  <el-table class="m-drag-table-container" ref="tableRef" :data="tableData.data" :key="'table' + tableData.key"
    style="width: 100%" :highlight-current-row="true" @selection-change="elmentSelectChangeHandle"
    @sort-change="sortChangeHandle">
    <slot name="slotCheckBox"></slot>

    <template v-for="item of tableData.columnList">
      <el-table-column v-if="isArray(item.prop) && props.sp.ctc.includes(item.label)" :label="item.label" align="center"
        :width="item.width || 120">
        <template #default="{ row }">
          <el-tag :type="row[item.prop].type" @click="row[item.prop].handle && row[item.prop].handle(row)">{{
            row[item.prop].value }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column v-if="!isArray(item.prop) && props.sp.ctc.includes(item.label)" show-overflow-tooltip
        :prop="item.prop" :label="item.label" align="center" :width="item.width || 120" :sortable="item.sortable" />
    </template>

    <slot name="slotOperation"></slot>
  </el-table>
</template>

<script lang="ts" setup>
import { nextTick, onMounted, reactive, ref } from 'vue';
import Sortable from 'sortablejs';
import { isArray } from '@/utils/util';

const emits = defineEmits(['handleSelectionChange', 'sortChangeHandle']);

const elmentSelectChangeHandle = (val: any) => {
  emits('handleSelectionChange', val);
};

const sortChangeHandle = ({ column, prop, order }) => {
  emits('sortChangeHandle', { column, prop, order });
}

const props = defineProps({
  columnList: {
    type: Array,
    default: []
  },
  tableData: {
    type: Array,
    default: []
  },
  isSlotSelect: {
    type: Boolean,
    default: false
  },
  sp: {
    type: Object,
    default: {}
  }
});

const tableData = reactive({
  key: new Date().getTime(),
  data: [],
  columnList: []
});

const tableRef = ref();
let sortable: Sortable;
onMounted(() => {
  tableData.data = props.tableData;
  tableData.columnList = props.columnList;

  initTableHeaderDrag();
});

watch(
  () => props.tableData,
  (data: any) => {
    tableData.data = data;
  }
);

function initTableHeaderDrag() {
  if (sortable) {
    sortable.destroy();
  }
  let el = tableRef.value.$el.querySelector('.el-table__header-wrapper tr');
  sortable = Sortable.create(el, {
    animation: 150,
    onEnd(evt: any) {
      let oldIndex = evt.oldIndex;
      let newIndex = evt.newIndex;

      if (props.isSlotSelect) {
        oldIndex--;
        newIndex--;
      }

      const oldItem = tableData.columnList[oldIndex];
      tableData.columnList.splice(oldIndex, 1);
      tableData.columnList.splice(newIndex, 0, oldItem);
      tableData.key = new Date().getTime();
      nextTick(() => {
        initTableHeaderDrag();
      });
    }
  });
}
</script>

<style lang="scss">
.m-drag-table-container th {
  cursor: move;
}
</style>
